const Router = require('koa-router')
// const jsonwebtoken = require('jsonwebtoken')
const jwt = require('koa-jwt')
const {
    secret
} = require('../config')
const router = new Router({
    prefix: '/users'
})
const {
    find,
    findById,
    create,
    update,
    delete: del,
    login,
    ListFollowing,
    follow,
    unfollow,
    ListFollower,
    checkUserExist
} = require('../controllers/users')

const auth = jwt({
    secret
})

const checkOwner = async (ctx, next) => {
    if (ctx.params.id !== ctx.state.user._id) {
        ctx.throw(403, '权限不足')
    }
    await next()
}

router.get('/', find)

router.get('/:id', findById)

router.post('/', create)

router.patch('/:id', auth, checkOwner, update)

router.delete('/:id', auth, checkOwner, del)

router.post('/login', login)

router.get('/:id/following', ListFollowing)

router.get('/:id/followers', ListFollower)

router.put('/following/:id', auth, checkUserExist, follow)

router.delete('/following/:id', auth, checkUserExist, unfollow)

module.exports = router